"use client";

import { useState, useCallback, useRef } from "react";
import { MazeGame, MazeHandle } from "@/components/maze/maze";
import { MazeControls } from "@/components/maze/maze-controls";
import { Direction } from "@/components/maze/maze-generator";
import { motion } from "framer-motion";
import { useMobile } from "@/hooks/use-mobile";

export default function Home() {
  const isMobile = useMobile();
  const [difficulty, setDifficulty] = useState<"easy" | "medium" | "hard">("medium");
  const [mazeKey, setMazeKey] = useState(0); // 用于强制重新渲染迷宫
  const [showCongrats, setShowCongrats] = useState(false);
  
  // 计算合适的单元格大小
  const getCellSize = () => {
    if (isMobile) {
      return difficulty === "hard" ? 18 : difficulty === "medium" ? 24 : 32;
    }
    return difficulty === "hard" ? 28 : difficulty === "medium" ? 36 : 48;
  };

  const handleMazeComplete = useCallback(() => {
    setShowCongrats(true);
    setTimeout(() => {
      setShowCongrats(false);
    }, 3000);
  }, []);

  const handleReset = useCallback(() => {
    setMazeKey(prev => prev + 1);
  }, []);

  const handleChangeDifficulty = useCallback((newDifficulty: "easy" | "medium" | "hard") => {
    setDifficulty(newDifficulty);
    setMazeKey(prev => prev + 1);
  }, []);

  // 迷宫实例的引用
  const mazeRef = useRef<MazeHandle>(null);

  // 处理方向控制
  const handleMove = useCallback((direction: Direction) => {
    if (!mazeRef.current) return;
    
    const { maze, player, setPlayer, setBreadcrumbs, completed, setCompleted, onComplete } = mazeRef.current;
    
    if (completed) return;

    if (maze && player) {
      const canMove = !maze.cells[player.y][player.x].walls[
        direction === 0 ? "top" : 
        direction === 1 ? "right" : 
        direction === 2 ? "bottom" : "left"
      ];

      if (canMove) {
        setBreadcrumbs((prev) => [...prev, player]);
        
        const newPosition = {
          x: player.x + (direction === 1 ? 1 : direction === 3 ? -1 : 0),
          y: player.y + (direction === 2 ? 1 : direction === 0 ? -1 : 0)
        };
        
        setPlayer(newPosition);

        if (newPosition.x === maze.end.x && newPosition.y === maze.end.y) {
          setCompleted(true);
          onComplete?.();
        }
      }
    }
  }, []);

  return (
    <main className="flex min-h-screen flex-col items-center justify-between p-4 md:p-24">
      <div className="z-10 max-w-5xl w-full items-center justify-center font-mono text-sm flex flex-col">
        <motion.h1 
          className="text-4xl md:text-6xl font-bold mb-8 neon-text"
          initial={{ opacity: 0, y: -20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5 }}
        >
          霓虹迷宫
        </motion.h1>
        
        <motion.div
          className="w-full flex flex-col items-center"
          initial={{ opacity: 0, scale: 0.9 }}
          animate={{ opacity: 1, scale: 1 }}
          transition={{ delay: 0.2, duration: 0.5 }}
        >
          <MazeGame 
            key={mazeKey}
            width={10} 
            height={10} 
            cellSize={getCellSize()}
            difficulty={difficulty}
            onComplete={handleMazeComplete}
            ref={mazeRef}
          />
          
          <MazeControls 
            onMove={handleMove}
            onReset={handleReset}
            onChangeDifficulty={handleChangeDifficulty}
            difficulty={difficulty}
          />
        </motion.div>
        
        {/* 背景装饰 */}
        <div className="fixed inset-0 -z-10 overflow-hidden">
          <div className="absolute top-0 left-0 w-1/3 h-1/3 bg-neon-pink opacity-5 blur-3xl rounded-full animate-float" />
          <div className="absolute bottom-0 right-0 w-1/2 h-1/2 bg-neon-blue opacity-5 blur-3xl rounded-full animate-float" style={{ animationDelay: "1s" }} />
          <div className="absolute top-1/2 right-1/4 w-1/4 h-1/4 bg-neon-green opacity-5 blur-3xl rounded-full animate-float" style={{ animationDelay: "2s" }} />
        </div>
        
        {/* 祝贺弹窗 */}
        {showCongrats && (
          <motion.div 
            className="fixed inset-0 flex items-center justify-center bg-black bg-opacity-70 z-50"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
          >
            <motion.div 
              className="bg-card p-8 rounded-lg border-2 border-neon-pink neon-border"
              initial={{ scale: 0.8, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              transition={{ type: "spring", damping: 12 }}
            >
              <h2 className="text-3xl font-bold mb-4 neon-text">恭喜!</h2>
              <p className="text-xl">你成功完成了迷宫挑战!</p>
            </motion.div>
          </motion.div>
        )}
      </div>
    </main>
  );
}